const codeContainer = document.getElementById('code-container');
const speedInput = document.getElementById('speed');
let currentTimeout;

// 粘贴代码功能
codeContainer.addEventListener('paste', (event) => {
    event.preventDefault(); // 阻止默认粘贴行为
    const text = (event.clipboardData || window.Clipboard).getData('text'); // 获取粘贴的文本
    codeContainer.textContent = text; // 将文本放入代码容器
});

// 点击时清除代码区域的提示文字
codeContainer.addEventListener('click', function () {
    if (this.textContent === '在这里粘贴你的代码...') {
        this.textContent = '';
    }
});

// 失去焦点时，如果内容为空，恢复提示文字
codeContainer.addEventListener('blur', function () {
    if (this.textContent.trim() === '') {
        this.textContent = '在这里粘贴你的代码...';
    }
});

// 监听鼠标滚轮，能调整写代码的速度
speedInput.addEventListener('wheel', (event) => {
    event.preventDefault();

    const step = 1; // 每次滚动的步长
    let value = parseInt(speedInput.value);

    if (event.deltaY < 0) {
        value += step;
    } else {
        value -= step;
    }

    // 确保值在范围内
    value = Math.max(1, Math.min(100, value));
    speedInput.value = value;
});

let config = null;

async function loadConfig() {
    try {
        const response = await fetch('./config.json'); // 加载配置文件
        if (!response.ok) {
            throw new Error('配置文件加载失败');
        }

        config = await response.json(); // 解析 JSON 数据
    } catch (error) {
        console.error('加载配置文件时出错:', error);
        alert('配置文件加载失败，请检查网络或配置文件路径！');
    }
}

// --------------匀速写代码功能--------------
async function startTyping() {
    if (!config) {
        await loadConfig(); // 如果配置文件未加载，先加载
    }

    const code = codeContainer.textContent; // 从代码容器中获取内容
    if (code.trim() === '在这里粘贴你的代码...') {
        alert('请粘贴代码到黑色代码框中！');
        return;
    }

    codeContainer.textContent = ''; // 清空代码容器
    let index = 0;

    if (currentTimeout) {
        clearTimeout(currentTimeout);
    }

    const processedChars = [];
    const { keywords, functions, classes, interfaces } = config; // 从配置中获取数据

    let currentWord = '';
    let inString = false;
    let inComment = false;
    let inMultiLineComment = false;

    for (let i = 0; i < code.length; i++) {
        const char = code[i];
        const nextChar = code[i + 1];

        // 处理多行注释的开始
        if (char === '/' && nextChar === '*' && !inString && !inComment) {
            inMultiLineComment = true;
            processedChars.push({ char, style: 'comment' });
            continue;
        }

        // 处理多行注释的结束
        if (char === '*' && nextChar === '/' && inMultiLineComment) {
            inMultiLineComment = false;
            processedChars.push({ char, style: 'comment' });
            continue;
        }

        // 处理单行注释
        if (char === '/' && nextChar === '/' && !inString && !inMultiLineComment) {
            inComment = true;
            processedChars.push({ char, style: 'comment' });
            continue;
        }

        // 如果遇到换行符，重置单行注释
        if (char === '\n') {
            inComment = false;
        }

        // 处理字符串
        if ((char === '"' || char === "'") && !inComment && !inMultiLineComment) {
            inString = !inString;
            processedChars.push({ char, style: 'string' });
            continue;
        }

        // 处理标点符号
        if (/[\(\)\{\}]/.test(char) && !inString && !inComment && !inMultiLineComment) {
            processedChars.push({ char, style: 'punctuation' });

            if (currentWord) {
                const style = keywords.includes(currentWord) ? 'keyword'
                    : functions.includes(currentWord) ? 'function'
                        : classes.includes(currentWord) ? 'class'
                            : interfaces.includes(currentWord) ? 'interface'
                                : 'default';

                for (const c of currentWord) {
                    processedChars.push({ char: c, style });
                }

                currentWord = '';
            }

            continue;
        }

        // 处理字符串内容
        if (inString) {
            processedChars.push({ char, style: 'string' });
            continue;
        }

        // 处理注释内容
        if (inComment || inMultiLineComment) {
            processedChars.push({ char, style: 'comment' });
            continue;
        }

        // 处理关键字、函数名、类名
        if (/[a-zA-Z]/.test(char)) {
            currentWord += char;

            if (!/[a-zA-Z]/.test(nextChar)) {
                const style = keywords.includes(currentWord) ? 'keyword'
                    : functions.includes(currentWord) ? 'function'
                        : classes.includes(currentWord) ? 'class'
                            : interfaces.includes(currentWord) ? 'interface'
                                : 'default';

                for (const c of currentWord) {
                    processedChars.push({ char: c, style });
                }

                currentWord = '';
            }
        } else {
            if (currentWord) {
                const style = keywords.includes(currentWord) ? 'keyword'
                    : functions.includes(currentWord) ? 'function'
                        : classes.includes(currentWord) ? 'class'
                            : interfaces.includes(currentWord) ? 'interface'
                                : 'default';

                for (const c of currentWord) {
                    processedChars.push({ char: c, style });
                }

                currentWord = '';
            }

            processedChars.push({ char, style: 'default' });
        }
    }

    if (currentWord) {
        const style = keywords.includes(currentWord) ? 'keyword'
            : functions.includes(currentWord) ? 'function'
                : classes.includes(currentWord) ? 'class'
                    : interfaces.includes(currentWord) ? 'interface'
                        : 'default';

        for (const c of currentWord) {
            processedChars.push({ char: c, style });
        }
    }

    function typeNextCharacter() {
        if (index < processedChars.length) {
            const { char, style } = processedChars[index];
            const span = document.createElement('span');

            if (style) {
                span.className = style;
            }

            span.textContent = char;
            codeContainer.appendChild(span);
            index++;

            const speed = parseInt(speedInput.value);
            currentTimeout = setTimeout(typeNextCharacter, speed);
        }
    }

    typeNextCharacter();
}